<template>
  <el-card class="box-card">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="width: 300px">
      <el-breadcrumb-item style="font-size: 16px">首页</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px">学校管理</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px"
        >推荐院校管理</el-breadcrumb-item
      >
    </el-breadcrumb>
    <div class="search">
      <el-input
        style="width: 200px"
        placeholder="请输入院校名称"
        v-model="collegeName"
        @blur="blur"
      ></el-input>
      <el-button
        @click="searchCollege"
        style="background-color: rgba(255, 101, 0); color: #fff"
        icon="el-icon-search"
        >搜索</el-button
      >
      <div>
        <h4 style="font-size: 16px; color: rgba(255, 0, 0)">{{ searchMsg }}</h4>
      </div>
    </div>
    <el-table
      :data="userData"
      border
      style="width: 1021px; margin-left: 30px"
      :header-cell-style="headClass"
    >
      <el-table-column
        label="序号"
        width="70"
        type="index"
        cell-style="font-weight: 700;"
        align="center"
      ></el-table-column>
      <el-table-column label="院校名称" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="院校图标" width="150" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.logo" min-width="50" height="50" />
        </template>
      </el-table-column>
      <el-table-column label="所在地区" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.province }}</span>
        </template>
      </el-table-column>
      <el-table-column label="院校类型" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.category }}</span>
        </template>
      </el-table-column>
      <el-table-column label="办学类型" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="院校特色" width="120" align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.ts }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button
            style="float: left"
            v-if="showEdit"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row.name)"
          ></el-button>
          <el-button
            style="float: left"
            v-if="showRemove"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeUniByName(scope.row.name)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="修改信息"
      :visible.sync="editDialogVisible"
      width="400px"
      @close="editDialogClosed"
      class="dialog"
      top="10px"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="院校名称" prop="name">
          <el-input
            v-model="editForm.name"
            autocomplete="off"
            maxlength="12"
          ></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="province">
          <el-input v-model="editForm.province" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="院校类型" prop="category">
          <el-input v-model="editForm.category" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="办学类型" prop="type">
          <el-input v-model="editForm.type" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="院校特色" prop="ts">
          <el-input v-model.number="editForm.ts" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      class="pagination"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-size="queryInfo.pagesize"
      layout="total, prev, pager, next"
      :total="queryInfo.count"
      background
    >
      <!--
        @current-change(页码发生改变时触发)
        :current-page(设置当前页码)
        :page-size(设置每页的数据条数)
        :total(设置总页数)
     -->
    </el-pagination>
  </el-card>
</template>

<script>
import qs from "qs";
import axios from "axios";
import throttling from "@/public/throttling.js";
export default {
  data() {
    var validateName = (rule, value, callback) => {
      // 只能输入汉字
      let reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("院校名称不能为空!"));
      } else {
        if (!reg.test(value)) {
          console.log("输入不合法");
          callback(new Error("只能输入汉字！"));
        } else if (value.search("大学") === -1) {
          callback(new Error("请正确填写院校名称！"));
        } else {
          console.log("输入合法");
          console.log(typeof value);
          callback();
        }
      }
    };
    var validateProvince = (rule, value, callback) => {
      let reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("省份不能为空!"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入汉字！"));
      } else {
        callback();
      }
    };
    var validateCategory = (rule, value, callback) => {
      let reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("院校类型不能为空!"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入汉字！"));
      } else {
        callback();
      }
    };
    var validateType = (rule, value, callback) => {
      let reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("办学类型不能为空!"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入汉字！"));
      } else {
        callback();
      }
    };
    var validateTs = (rule, value, callback) => {
      if (!Number.isInteger(value) || value !== 985 || value !== 211) {
        callback(new Error("必须填985或211！"));
      } else {
        callback();
      }
    };
    return {
      editFormRules: {
        name: [
          {
            validator: validateName,
            trigger: "blur",
          },
        ],
        province: [
          {
            validator: validateProvince,
            trigger: "blur",
          },
        ],
        category: [
          {
            validator: validateCategory,
            trigger: "blur",
          },
        ],
        type: [
          {
            validator: validateType,
            trigger: "blur",
          },
        ],
        ts: [
          {
            validator: validateTs,
            trigger: "blur",
          },
        ],
      },
      // 院校搜索
      collegeName: "",
      // 有效性验证
      searchMsg: "",
      // 按钮显示隐藏
      showEdit: true,
      showRemove: true,
      // 控制修改院校
      editDialogVisible: false,
      // 修改用户的表单数据
      editForm: {
        fname: "",
        name: "",
        province: "",
        category: "",
        type: "",
        ts: "",
      },
      //初始分页条件
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 4,
        count: 0,
      },
      // 保存请求回来的用户列表数据
      userData: [
        {
          category: "1",
          code: 10003,
          feature: null,
          heat: 3001,
          is211: "211",
          is985: "985",
          ts: "",
          logo: "https://static-data.eol.cn/upload/logo/140.jpg",
          name: "清华大学1",
          province: "北京",
          type: "1",
          unvid: 2,
        },
      ],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      formLabelWidth: "120px",
    };
  },
  methods: {
    // 表格表头
    headClass() {
      //表头居中显示
      return "color:rgba(0,0,0,.8);font-weight:bold;font-size:16px";
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    handleCurrentChange: throttling(function (page) {
      this.queryInfo.pagenum = page;
      console.log(this.queryInfo.pagenum);
      console.log("跳转了");
      // 重新按照pagenum发送请求 请求最新的数据
      if (this.collegeName === "") {
        this.getUniList_Token();
      } else {
        this.$axios
          .get("/back/university/" + this.collegeName, {
            params: {
              name: this.collegeName,
              page: this.queryInfo.pagenum,
              size: this.queryInfo.pagesize,
            },
          })
          .then((res) => {
            console.log(res);
            this.userData = res.data.data;
            this.queryInfo.count = res.data.code;
          });
      }
    }, 200),
    getUniList_Token() {
      const token = window.sessionStorage.getItem("tokenvalue");
      this.$axios.defaults.headers.common["satoken"] = token;
      this.$axios
        .get("/back/universities", {
          params: {
            page: this.queryInfo.pagenum,
            size: this.queryInfo.pagesize,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.data.status === 666) {
            this.$message.error("请先登录");
            this.$router.replace("/login");
          } else {
            this.userData = res.data.data;
            this.queryInfo.count = res.data.code;
          }
        });
    },
    showEditDialog(name) {
      this.editForm.fname = name;
      //显示弹出窗
      this.editDialogVisible = true;
    },
    editDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.editFormRef.resetFields();
    },
    cancel() {
      this.editDialogVisible = false;
      this.$message("取消修改");
    },
    editUser: throttling(function () {
      // 用户点击修改表单中的确定按钮之后，验证表单数据
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return error;
        else {
          const token = window.sessionStorage.getItem("tokenvalue");
          this.$axios.defaults.headers.common["satoken"] = token;
          // 发送请求 完成修改用户的操作
          this.$axios
            .put(
              "/back/university",
              qs.stringify({
                fName: this.editForm.fname,
                name: this.editForm.name,
                province: this.editForm.province,
                category: this.editForm.category,
                type: this.editForm.type,
                ts: this.editForm.ts,
              })
            )
            .then((res) => {
              console.log(res);
              if (res.status === 200) {
                this.$message.success("修改院校成功");
                //关闭对话框
                this.editDialogVisible = false;
                //重新请求最新的数据
                this.getUniList_Token();
              }
            });
        }
      });
    }, 200),
    // 删除院校
    removeUniByName(name) {
      //弹出确定取消框，是否删除用户
      this.$confirm("请问是否要永久删除该院校", "删除提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
      })
        .then(() => {
          //发送请求根据id完成删除操作
          this.$axios.delete("/back/university/" + name).then((res) => {
            console.log(res);
            //判断如果删除失败，就做提示
            if (res.data.code === 666) {
              this.$message.error("请先登录！");
              this.$router.replace("/login");
            } else if (res.data.code === 500) {
              this.$message.error("权限不足！");
            } else if (res.data.code === 200) {
              // //修改成功的提示
              this.$message.success("删除院校成功");
              // //重新请求最新的数据
              this.getUniList_Token();
            }
          });
        })
        .catch((action) => {
          this.$message({
            type: "info",
            message: action === "cancel" ? "取消删除" : "放弃删除",
          });
        });
    },
    // 失焦时间
    blur() {
      if (this.collegeName === "") {
        this.searchMsg = "";
        this.getUniList_Token();
      }
    },
    searchCollege: throttling(function () {
      let reg = /[^\u4E00-\u9FA5]/g;
      if (this.collegeName === "") {
        this.searchMsg = "";
      } else {
        if (reg.test(this.collegeName)) {
          console.log("不正确");
          this.searchMsg = "请正确输入名称";
          return;
        } else {
          console.log("正确");
          this.searchMsg = "";
          this.$axios
            .get("/back/university/" + this.collegeName, {
              params: {
                name: this.collegeName,
                page: this.queryInfo.pagenum,
                size: this.queryInfo.pagesize,
              },
            })
            .then((res) => {
              console.log(res);
              this.userData = res.data.data;
              this.queryInfo.count = res.data.code;
            });
        }
      }
    }, 200),
  },
  created() {
    this.$axios.get("/back/university/updateButton").then((res) => {
      if (res.data.code === 500) {
        this.showEdit = false;
      }
    });
    this.$axios.get("/back/university/deleteButton").then((res) => {
      console.log(res);
      if (res.data.code === 500) {
        this.showRemove = false;
      }
    });
    this.getUniList_Token();
  },
};
</script>

<style scoped>
.box-card {
  position: relative;
  margin: 22px auto;
  height: 550px;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.search {
  margin-top: 20px;
  margin-left: 40px;
}

.search .el-input:focus {
  border: rgba(255, 101, 0);
}

.el-table {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.dialog /deep/ .el-dialog {
  margin-top: 3vh;
}

.dialog /deep/ .el-dialog__body {
  padding: 0 20px;
}

.pagination {
  position: absolute;
  bottom: 20px;
  width: 412px;

  left: 50%;
  margin-left: -206px;
}
</style>